<?php
/**
 * Created by PhpStorm.
 * User: xuic
 * Date: 2016/6/1
 * Time: 9:53
 */
namespace work;

use app\ctr;
use C\lib\Db;

use C\mod\sack;
use C\mod\crate;
use C\mod\pieceState;
use C\mod\orderPiece;
use C\mod\finance;

class rallyPoint extends base{


    // --- 集结点派件筐列表（扫码卸筐下的列表） ---
    public function crateLists() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            if(!isset($post['lastId']) )  $sqlLimit = ' area_id_recipient >= 0 ';
            else   $sqlLimit = ' area_id_recipient < '.$post['lastId'];

            $stmt = Db::query('SELECT type FROM ' . DB_PRE . 'worker_type WHERE worker_id ="' . $worker->id . '" and type=1');
            if( $stmt && $stmt->rowCount() > 0) {

                // 为收派员，显示其所在区域的状态为０的待收件

                $stmt2 = Db::query ('select if(isNull(cda.name),"未划分区",cda.name) AS areaName , count(cdo.area_id_recipient) AS pieceCount , cdo.area_id_recipient AS areaId from cd_order_piece cdo LEFT JOIN cd_area cda  ON cda.id = cdo.area_id_recipient WHERE  cdo.state_in=9 AND  cdo.worker_id='.$worker->id . ' AND '. $sqlLimit.'  GROUP BY cdo.area_id_recipient ORDER BY areaId DESC LIMIT 10'); // state_in =9 表到集散

                $jPiece = [];
                if($stmt2 && $stmt2->rowCount() >= 0) {

                    while($data = $stmt2->fetch(\PDO::FETCH_ASSOC)) {
                        //                        $data['sackCount'] = $data['sackCount'] ? $data['sackCount'] : 0;
                        $jPiece[] = $data;
                    }
                }
                $this->writeAesJson( 1 , ['jPieces'=> $jPiece] , 1);
            } else
                $this->writeAesJson( 0 , '非集结点' ,1 );
        }

    }


    // --- 集结点收件列表 ---
    public function pouchLists() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            if (isset($post['lastId'])) {
                $lastId = $post['lastId'] + 0;
                $lastId = $lastId <= 0 ? 0 : $lastId;
            } else {
                $lastId = 0;
            }
            if($lastId == 0) $sqlLimit = ' cityId >= 0 ';
            else  $sqlLimit = ' cityId < '.$lastId;

            $stmt = Db::query('SELECT type FROM ' . DB_PRE . 'worker_type WHERE worker_id ="' . $worker->id . '" and type = 1');

            if($stmt && $stmt->rowCount() > 0) {

                // 为收派员，显示其所在区域的状态为０的待收件
                $stmt2 = Db::query('SELECT cityId , if(isNull(cityName),"",cityName) cityName , pieceCount ,if(isNull(sackCount),0,sackCount) sackCount FROM (select cdc.name AS cityName , count(distinct cdo.id) AS pieceCount , cdo.city_id_recipient AS cityId  from cd_order_piece cdo  LEFT JOIN cd_city cdc ON(cdc.id= cdo.city_id_recipient) WHERE cdo.state_in= 3   AND cdo.worker_id='.$worker->id .'   GROUP BY cdo.city_id_recipient ) AS a LEFT JOIN (SELECT cdo.city_id_recipient  cityId_b ,count(DISTINCT sack_id)  sackCount FROM cd_order_piece cdo WHERE  sack_id<>"" AND state_in=3  AND worker_id='.$worker->id .'   GROUP BY cdo.city_id_recipient )  b ON a.cityId = b.cityId_b WHERE '. $sqlLimit.' ORDER BY cityId DESC LIMIT 10'); // state_in =3 表已集散

                $jSack = [];
                if($stmt2 && $stmt2->rowCount() > 0) {
                    while ($data = $stmt2->fetch(\PDO::FETCH_ASSOC)) {
                        $data['sackCount'] = $data['sackCount'] ? $data['sackCount'] : 0;
                        $jSack[] = $data;
                    }
                }
                $this->writeAesJson( 1 , ['jPieces' => $jSack] , 1);
            } else
                $this->writeAesJson( 0 , '非集结点' ,1 );
        }
    }

    // --- 检测所传件中,是否有在其它袋的情况,若有,修正,对其它的袋进行减操作,包括 count 和 is_finish 判断 ---
    // --- count 值为 0 时, is_finish 值设为 1, 表使用完
    // --- 修改成功或无需修改返回 true ,否则返回 false
    private function amendSack( $pCodes ) {

        $flag = true;
        $strTmp = '"' . implode('","', $pCodes) . '"';

        $stmt = Db::query('SELECT sack_id as sackId FROM cd_order_piece WHERE  sack_id !="" AND piece_code IN ('.$strTmp.') ');

        if( $stmt && $stmt->rowCount() > 0 ) {

            while($data = $stmt->fetch(\PDO::FETCH_ASSOC)) $arr[] = $data['sackId']; // 返回袋号

            $arr2 = array_count_values($arr);

            foreach( $arr2 as $k => $v ) {
                $stmt2 = Db::prepare('UPDATE cd_sack SET count = count-:num , is_finish=if(count<=0,1,0) WHERE count-:num>=0 and id=:sackid');
                if( !($stmt2->execute([':sackid'=> $k , ':num' => $v]) && $stmt2->rowCount()>0) ) {
                    $flag = false;
                    break;
                }
            }
        }

        return $flag;
    }

    // --- 添加 cd_piece_state 表中所有件的内部状态 ---
    // --- @param $flag 值为false 表 $pieceCodes 传的是件号
    //                  值为true  表 $pieceCodes 传的是件ID
    // --- @param $stateIn  表要修改成的内部状态值
    public function addPieceStates( $pieceCodes , $workerId ,$stateIn , $flag=false ,$noSitePieceCode=[]) {

        if( $flag ) {
            $pieceArr = $pieceCodes;
        } else {
            $strTmp = '"' . implode('","', $pieceCodes) . '"';
            $stmt = Db::query('SELECT id  FROM cd_order_piece WHERE  piece_code IN ('.$strTmp.') ');
        }

        if( $flag || ( $stmt && $stmt->rowCount() > 0 ) ) {


            if( !$flag ) {
                while($data = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                    $pieceArr[] = $data['id'];
                } // 获得所有袋的ID
            }

            foreach($pieceArr as $v)
                $dates[] = [
                    'worker_id' => $workerId,
                    'piece_id' => $v,
                    'state_in' => $stateIn,
                    'state' => 1,
                    'user_show' => ($stateIn==7) ? 1 : 0,
                    'time_add' => $_SERVER['REQUEST_TIME']
                ];

            $keyArr = array_keys($dates[0]);

            $pieceState = new pieceState();
            $k = 0;
            do {
                if($k++ >= 3) break;   // 3次失败机会
            } while(!$pieceState->insert($keyArr, $dates));

            if($k <= 3) {
               Db::commit();
                if(count($noSitePieceCode)) {
                    $noSite = implode(',',$noSitePieceCode);
                    $this->writeAesJson(1, ['jpiececode'=>$noSite], 1);
                } else
                    $this->writeAesJson(1, [], 1);
            } else {
                Db::rollBack();
                $this->writeAesJson(0, '件内部状态添加失败', 1);
            }
        } else {
            $str1 = $pieceCodes;
            if(is_array($pieceCodes)) $str1 = '：'.implode(',',$pieceCodes);
            $this->writeAesJson(0, '查询件信息失败'.$str1, 1);
        }
    }



    // --- 集结点把件装袋,或集结点间转接袋 ---
    public function pouchAdd() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            $stmt = Db::query('SELECT TYPE FROM ' . DB_PRE . 'worker_type WHERE worker_id ="' . $worker->id . '" AND type=1');

            if($stmt && $stmt->rowCount() > 0) {

                if(isset($post['cityId']) && trim($post['cityId']) != '') {

                    if(isset($post['pieceCodes']) && ($pcount = count($post['pieceCodes']))) {

                        if(isset($post['count']) && ($post['count']=$post['count']+0)!=0) {

                            $pieceArr = array_unique($post['pieceCodes']);
                            if(count($pieceArr) == $post['count']) {

                               // 判断是否余额扫件后是否低于500元
                               if(!in_array($worker->id , static::$specialPoint)) {
                                   //不是分拨中心
                                   if(($wfinace = finance::get(['worker_id'=>$worker->id]))) {
                                       $tmpPrice = bcmul($post['count'], static::$center_price, 1);

                                       if(($wfinace->balance - $tmpPrice) >= self::lowPrice) {
                                           //余额够
                                       } else {
                                           $this->writeAesJson(0, '用户余额不足，请充值', 1);
                                           return false;
                                       }
                                   }else {
                                       $this->writeAesJson(0, '无此用户余额信息，请联系管理员', 1);
                                       return false;
                                   }
                               }

                                $pieceArr = array_filter($pieceArr);//去空


                                // --- 过滤重复扫描 ---
                                $rescanPieces = [];
                                $tmpPiece = Db::query('select piece_code from cd_order_piece where worker_id='.$worker->id .' AND state_in >=3 AND  piece_code IN ("' . implode('","', $pieceArr) . '")');
                                while($data = $tmpPiece->fetch(\PDO::FETCH_ASSOC))
                                    $rescanPieces[] = $data['piece_code'];
                                if($r = count($rescanPieces)) {
                                    if($r ==  $post['count']) {
                                        $this->writeAesJson(0, '所扫件码都已被该操作站点收入，请勿重复扫描', 1);
                                        return false;
                                    }else {
                                        $pieceArr = array_diff($pieceArr , $rescanPieces); //过滤
                                    }
                                }
                                $strTmp = '"' . implode('","', $pieceArr) . '"';

//                                // --- 无重复件时,检查所有件收件地址 ---
//                                $stmt2 = Db::query('SELECT piece_code FROM cd_order_piece WHERE city_id_recipient !='.trim($post["cityId"]).' AND piece_code IN ('.$strTmp.') ');
//
//                                if( $stmt2 && $stmt2->rowCount() <= 0 ) {

                                Db::beginTransaction();
                                $noSitePieceCode = [];

                                $isCentered = 0; // 是否被中心收取过费用
                                $isCenteredPieces = [] ; // 已被中沁收取过费用的件码
                                // --- 过滤出已被中心收取过费用的件 ---
                                $tmpPiece = Db::query('select piece_code  from cd_order_piece where isCentered=1 AND  piece_code IN ('.$strTmp.')');
                                while($data = $tmpPiece->fetch(\PDO::FETCH_ASSOC))
                                    $isCenteredPieces[] = $data['piece_code'];

                                $pieceArr = array_diff($pieceArr, $isCenteredPieces);

                                if(count($pieceArr))
                                    $strTmp = '"' . implode('","', $pieceArr) . '"';
                                else
                                    $strTmp ='';

                                // --- 2016-10-18 新增财务计费功能，暂不考虑袋的情况 by 徐剑锋 ---
                                if( in_array($worker->id , static::$centerPoint ) &&  ($strTmp != '')) {

                                    $tmpPiece = Db::query('select count(id) counts from cd_order_piece where state_in=3 and worker_id not in('.implode(',',static::$centerPoint).') and piece_code  IN ('.$strTmp.') ');
                                    $tmpCount = $tmpPiece->fetch(\PDO::FETCH_ASSOC);
                                    if($tmpCount['counts']!=$post['count']) {
                                        $tmpPiece = Db::query('select piece_code , worker_id from cd_order_piece where state_in=3  and piece_code  IN ('.$strTmp.') ');

                                        $pieceArr2 = [];
                                        $pieceArr3 = [];

                                        while($data = $tmpPiece->fetch(\PDO::FETCH_ASSOC)) {
//                                            if( !in_array($data['worker_id'] , static::$centerPoint))
                                            if($data['worker_id'] != $worker->id)
                                                $pieceArr2[]= $data['piece_code'];
                                            $pieceArr3[] = $data['piece_code'];
                                        }
                                        if(count($pieceArr2)==0) {
                                            $this->writeAesJson(0, '所扫描件没经过站点，或，已是该分拨中心的件了。', 1);
                                            return false;
                                        }
                                        $noSitePieceCode = array_diff($pieceArr, $pieceArr3);
                                        unset($pieceArr3);

                                        $pieceArr = $pieceArr2;

                                        $strTmp = '"' . implode('","', $pieceArr) . '"';
                                        $post['count'] = $tmpCount['counts'];
                                        unset($pieceArr2);
                                    }

                                    $center = Db::query('select count(id) counts ,group_concat(\'"\',piece_code,\'"\') piece_codes , worker_id from cd_order_piece where state_in=3 and worker_id not in('.implode(',',static::$centerPoint).') and piece_code  IN ('.$strTmp.') group by worker_id ');

                                    $datesArr = [];
                                    $totalCount =0;
                                    $k = 0;
                                    $workerids = [];
                                    $sql ='';
                                    $piece_count = [];
                                    $time_sql = '';
                                    $workerPcodes = [];
                                    // --- 更新 cd_finance 表 ---
                                    while ($tmpData = $center->fetch(\PDO::FETCH_ASSOC)) {
                                        if( in_array($tmpData['worker_id'] , static::$centerPoint)) continue;
                                        $sql .= ' WHEN :id' . $k . ' THEN :balan' . $k;
                                        $time_sql .= ' WHEN :id'.$k.' THEN '.$_SERVER['REQUEST_TIME'];
                                        $datesArr = array_merge($datesArr, [':id'.$k => $tmpData['worker_id'], ':balan'.$k => $tmpData['counts']*static::$center_price]);
                                        $totalCount += ($tmpData['counts']+0);  
                                        $workerids[$k] = $tmpData['worker_id']; 
                                        $piece_count[$tmpData['worker_id']] = $tmpData['counts'];

                                        $workerPieceCodes[$tmpData['worker_id']] = $tmpData['piece_codes'];
                                        ++$k;
                                    }

                                    if(count($workerids)==0) {
                                        $this->writeAesJson(0, '所扫件已是该分拨中心的件，无他人件', 1);
                                        return false;
                                    }

                                    if($sql!='') {
//                                        $sql = "UPDATE cd_finance SET balance = balance - CASE worker_id ".$sql;
//                                        $sql .= ' WHEN '.static::$centerPoint.' THEN '.$totalCount * -static::$center_price ;
//                                        $sql .= ' END, time_update = CASE worker_id '.$time_sql.' WHEN '.static::$centerPoint.' THEN '.$_SERVER['REQUEST_TIME'] .' END WHERE worker_id IN ('.implode(',',$workerids).','.static::$centerPoint.')';

                                        $sql = "UPDATE cd_finance SET balance = balance - CASE worker_id ".$sql;
                                        $sql .= ' WHEN '.$worker->id.' THEN '.$totalCount * -static::$center_price ;
                                        $sql .= ' END, time_update = CASE worker_id '.$time_sql.' WHEN '.$worker->id.' THEN '.$_SERVER['REQUEST_TIME'] .' END WHERE worker_id IN ('.implode(',',$workerids).','.$worker->id.')';

                                        $preFinance = Db::prepare($sql);
                                        unset($sql);
                                        if( $preFinance->execute($datesArr) && ($row=$preFinance->rowCount())>=$k ){

                                            //  --- 添加 cd_finance_detail 表 ---
                                            $fdetail = [];

                                            foreach($workerids as $k=> $v) {
                                                $fdetail[] = [
                                                    'worker_id' => $v,
                                                    'worked_id' => $worker->id,
                                                    'scan_type' => 0,
                                                    'pay_type' => 1, // 1是负
                                                    'price' => 0-$datesArr[':balan'.$k] ,
                                                    'piece_ids'=> $workerPieceCodes[$v],
                                                    'piece_count'=> $piece_count[$v],
                                                    'time_add' => $_SERVER['REQUEST_TIME'],
                                                    'status' => 1 // 正常
                                                ];
                                            }
                                            unset($workerPieceCodes);

                                            $fdetail[] = [
                                                'worker_id' => $worker->id,
                                                'worked_id' => implode(',',$workerids),
                                                'scan_type' => 1,
                                                'pay_type' => 0, // 0是正
                                                'price' => $totalCount*static::$center_price ,
                                                'piece_ids'=>$strTmp,
                                                'piece_count'=>array_sum($piece_count),
                                                'time_add' => $_SERVER['REQUEST_TIME'],
                                                'status' => 1 // 正常
                                            ];
                                            $keyArr = array_keys($fdetail[0]);

                                            $financeDetail = new \C\mod\finance_details();
                                            $k = 0;
                                            do {
                                                if(++$k > 3)  break;  // 3次失败机会
                                            } while(!($tt=$financeDetail->insert($keyArr, $fdetail)));

                                            if($k <= 3) {
                                                unset($fdetail, $workerids, $datesArr);
                                                $isCentered = 1;
                                            } else {
                                                Db::rollBack();
                                                $err = '';
                                                foreach($fdetail as $v);
                                                    $err .= implode(' , ',$v).' ; ';

                                                \C\log( '［分拨中心］财务路由添加失败，分拨中心收站1   \n workerids='.implode(',',$workerids ).'  \n datas='.$err);
                                                $this->writeAesJson(0, '财务路由添加失败', 1);
                                                return false;
                                            }
                                            // --- / 添加 cd_finance_detail 表 ---
                                        }else {
                                            \C\log( '［分拨中心］财务信息更新失败，分拨中心收站1   \n workerids='.implode(',',$workerids).'  \n datas='.implode(' , ' , $datesArr));
                                            Db::rollBack();
                                            $this->writeAesJson(0, '财务信息更新失败', 1);
                                            return false;
                                        }
                                    }

                                }


                                if( rallyPoint::amendSack($post['pieceCodes']) ) {

                                    $tmpScode = isset($post['sackCode']) ? trim($post['sackCode']) : '';

                                    if($tmpScode) {
                                        // --- 有件号,有袋号的情况 ---
                                        if($stmt3 = sack::get(['code' => $tmpScode])) {

                                            if($stmt3->is_finish == 1) {

                                                // 值1表该袋使用完,为可使用状态,执行装袋
                                                $preSack = Db::prepare('UPDATE ' . DB_PRE . 'sack SET worker_id=:worker_id ,count=:count , is_finish=0 WHERE code=:code');
                                                if($preSack->execute([':code' => $tmpScode , ':count'=>$post['count'] , ':worker_id' => $worker->id])
                                                    && ($preSack->rowCount() > 0)) {
                                                    $stmt4 = Db::prepare('UPDATE cd_order_piece SET state_in=3 ,sack_id=:sackId ,worker_id=:worker_id WHERE state_in <=3 AND state_in >=2 AND piece_code IN (' . $strTmp . ') ');
                                                    if($stmt4->execute([':sackId' => $stmt3->id, ':worker_id' => $worker->id]) && ($stmt4->rowCount() >= 0)) {
                                                        rallyPoint::addPieceStates($pieceArr , $worker->id , 3);
                                                    } else
                                                        $this->writeAesJson(0, '件状态更新失败', 1);
                                                } else
                                                    $this->writeAesJson(0, '袋所有者更新失败', 1);
                                            } else
                                                $this->writeAesJson(0, '该袋已在使用中无法添加件', 1);
                                        } else {
                                            // --- 创建新袋 ---
                                            $nullSack = Db::prepare('INSERT INTO '. DB_PRE .'sack (code,is_finish,count,city_id,worker_id,time_add) values(:code,:is_finish,:count,:city_id,:worker_id,:time_add)');
                                            $sackDate=[
                                                ':code' => strtoupper( $tmpScode ), // ''
                                                ':is_finish' => 0,
                                                ':count' => $post['count'],
                                                ':city_id' => $post['cityId'],
                                                ':worker_id' => $worker->id,
                                                ':time_add' => $_SERVER['REQUEST_TIME']
                                            ];
                                            if( $nullSack->execute($sackDate) && $nullSack->rowCount() > 0 ) {
                                                $addSackId = Db::getInsertID();

//                                                $stmt4 = Db::prepare('UPDATE cd_order_piece SET state_in=3 ,sack_id=:sackId ,worker_id=:worker_id WHERE state_in <=3 AND state_in >=2  AND piece_code IN (' . $strTmp . ') ');
                                                $stmt4 = Db::prepare('UPDATE cd_order_piece SET state_in=3 ,sack_id=:sackId ,worker_id=:worker_id WHERE  piece_code IN (' . $strTmp . ') ');
                                                if($stmt4->execute([':sackId' => $addSackId, ':worker_id' => $worker->id]) && ($stmt4->rowCount() > 0)) {
                                                    rallyPoint::addPieceStates($pieceArr , $worker->id , 3);
                                                } else
                                                    $this->writeAesJson(0, '件状态更新失败', 1);
                                            }
                                        }
                                    } else {

                                            // --- 有件号无袋号的情况，无需添加袋信息,件中无sack_id ---
                                        $sIn =  3;
                                        if(count($isCenteredPieces)) {
                                            $strTmp .= (trim($strTmp)==''?'':',') . '"' . implode('","', $isCenteredPieces) . '"';
                                            $pieceArr = array_merge($pieceArr , $isCenteredPieces);
                                        }

                                        $stmt4 = Db::prepare('UPDATE cd_order_piece SET state_in= ' . $sIn . ($isCentered?', isCentered=1':'').'  ,worker_id=:worker_id WHERE state_in <=3 AND state_in >=2  AND piece_code IN (' . $strTmp . ') ');
                                        if($stmt4->execute([':worker_id' => $worker->id]) && ($stmt4->rowCount() >= 0)) {
                                            rallyPoint::addPieceStates($pieceArr, $worker->id, $sIn ,false,$noSitePieceCode);
                                        } else
                                            $this->writeAesJson(0, '件状态更新失败', 1);
                                    }
                                } else
                                    $this->writeAesJson(0, '件原所属袋信息修正失败', 1);
                                //                                } else {
                                //                                    while($data = $stmt2->fetch(\PDO::FETCH_ASSOC)) $jPieceCodes[] = $data; // 返回的冲突的件号
                                //
                                //                                    $this->writeAesJson(0, ['msg' => '件收件人地址与指定目的地冲突', 'pieceCodes' => $jPieceCodes], 1);
                                //                                }
                            } else
                                $this->writeAesJson(0, '件实际数量'.(count($pieceArr) > $post['count'] ? '>' : '<') .'提交的数量', 1);
                        } else
                            $this->writeAesJson(0, '无件数提交或提交格式非整形', 1);
                    } else {
                        // --- 有袋号无件号 ---
                        if(isset($post['sackCode']) && $post['sackCode'] != '' && ($sack = sack::get(['code' => $post['sackCode']]))) {

                            if( $sack && $sack->is_finish === '0' ) {
                                if($sack->worker_id != $worker->id) {

                                    if( ($pieceStmts = Db::query('SELECT piece_code as pieceCode ,city_id_recipient FROM '. DB_PRE .'order_piece WHERE state_in <=3 AND state_in >=2 and sack_id='. $sack->id))  &&  $pieceStmts->rowCount() > 0 ) {

                                        $pieceCodes = []; $pieceRecity = [];
                                        while ($tmpData = $pieceStmts->fetch(\PDO::FETCH_ASSOC)) {
                                            $pieceCodes[] = $tmpData['pieceCode'];// 存放所有件ID
                                            $pieceRecity[] = $tmpData['city_id_recipient'];
                                        }
                                        $tmpPR = array_unique($pieceRecity);
                                        //                                        if(count($tmpPR)==1 && $tmpPR[0] == $post['cityId']) {
                                        Db::beginTransaction();
                                        $preSack = Db::prepare('UPDATE ' . DB_PRE . 'sack SET worker_id=:worker_id WHERE code=:code');
                                        if($preSack->execute([':code' => strtoupper( trim($post['sackCode'])), ':worker_id' => $worker->id])) {

                                            if($preSack->rowCount() > 0) {

                                                $prePieces = Db::prepare('UPDATE  ' . DB_PRE . 'order_piece SET worker_id=:worker_id,state_in=3 WHERE state_in <=3 AND state_in >=2 and sack_id=:sackId');

                                                if($prePieces->execute([':worker_id' => $worker->id, ':sackId' => $sack->id]) && ($prePieces->rowCount() >= 0)) {
                                                    rallyPoint::addPieceStates($pieceCodes, $worker->id, 3);
                                                } else
                                                    $this->writeAesJson(0, '该袋所装的件移交失败', 1);
                                            } else
                                                $this->writeAesJson(0, '该袋移交失败', 1);
                                        } else
                                            $this->writeAesJson(0, '移交袋失败,该袋可能非集结点的袋');
    //                                        } else
    //                                            $this->writeAesJson(0, '袋中的件所发地不同或与指定目的地冲突',1);
                                    } else
                                        $this->writeAesJson(0, '该袋所装的件信息获取失败或无件信息', 1);
                                } else
                                    $this->writeAesJson(0, '已是本集点的袋', 1);
                            } else
                                $this->writeAesJson(0, '该袋号已使用完,请同时扫描件号添加到该袋', 1);
                        } else
                            $this->writeAesJson(0, '是新袋请提交要装的件号', 1);
                    }
                } else
                    $this->writeAesJson(0, '无城市ID提交', 1);
            } else
                $this->writeAesJson(0, '非集结点', 1);
        }

    }



    // --- 集结点“扫码卸筐” ---
    public function scanCrate() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            $stmt = Db::query('SELECT TYPE FROM ' . DB_PRE . 'worker_type WHERE worker_id ="' . $worker->id . '" AND type=1');

            if($stmt && $stmt->rowCount() > 0) {
                if( isset($post['crateCodes']) && count($post['crateCodes']) ) {

                    // --- 1.1 有框号,有件号时 ---
                    $strTmp = '"' . implode('","', $post['crateCodes']) . '"';

                    // --- 无重复件时,检查所有件收件地址 ---
                    $crateStmt = Db::query('SELECT id FROM cd_crate WHERE is_finish=0 and code IN ('.$strTmp.') ');
                    if( $crateStmt && $crateStmt->rowCount()>0 ) {
                        $cratesArr = [];
                        while ($tmpData = $crateStmt->fetch(\PDO::FETCH_ASSOC))  $cratesArr[] = $tmpData['id'];// 存放所有框ID

                        Db::beginTransaction();

                        // --- 1.1.1 更新件的 state_in=9 , 注:只有状态为 8 的件才能更新 ---
                        $strTmp = '"' . implode('","',  $cratesArr) . '"';

                        $pieceStmt = Db::prepare('SELECT id FROM cd_order_piece WHERE state_in=8 AND crate_id IN ('.$strTmp.')' );
                        if( $pieceStmt->execute() && $pieceStmt->rowCount() >0) {

                            // --- 先更新件的状态 ---
                            $stmt = Db::prepare('UPDATE '. DB_PRE .'order_piece SET state_in=9 , worker_id=:worker_id WHERE state_in=8   AND crate_id IN ('.$strTmp.')' );
                            if( $stmt->execute([':worker_id' => $worker->id]) && ($stmt->rowCount() > 0) ) {

                                // --- 更新框状态 ---
                                $strTmp = '"' . implode('","',  $cratesArr) . '"';

                                $crateStmt1 = Db::prepare('UPDATE ' . DB_PRE . 'crate SET worker_id=:worker_id , is_finish=1 , count=0 WHERE id IN ('.$strTmp.')' );
                                if( $crateStmt1->execute([':worker_id' => $worker->id]) && ($crateStmt1->rowCount() >0) ) {
                                    $pieceIds = [];
                                    while ($tmpData = $pieceStmt->fetch(\PDO::FETCH_ASSOC)) $pieceIds[] = $tmpData['id']; // 存放所有件ID
                                    rallyPoint::addPieceStates( $pieceIds , $worker->id , 9 ,true );

                                } else
                                    $this->writeAesJson(0, '框状态更新失败', 1);
                            } else
                                $this->writeAesJson(0, '件状态更新失败或有非干线上提交来的件', 1);
                        } else
                            $this->writeAesJson(0, '此框下无件号或件内部状态非8(上支线)', 1);

                    } else
                        $this->writeAesJson(0, '此框下无件号或已卸框', 1);
                } else
                    $this->writeAesJson(0, '无框号提交', 1);
            } else
                $this->writeAesJson(0, '非集结点', 1);
        }
    }


    public function isCenter() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if(in_array($worker->id , static::$centerPoint))
                $this->writeAesJson(1, ['flag'=>1], 1);
            else
                $this->writeAesJson(1, ['flag'=>0 ], 1);

        }
    }



    public function isOkPiece() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if(trim($post['pieceCode'])!='') {
                if(is_string($post['pieceCode'])) {
                    $piece = orderPiece::get(['piece_code'=>$post['pieceCode']]);

                    if($piece) {

                        if($piece->state_in<3) {
                            $this->writeAesJson(0, '没有经过站点', 1);
                        }else if($piece->state_in==3 && (in_array($piece->worker_id , static::$centerPoint) && ($worker->id == $piece->worker_id))) {
                            $this->writeAesJson(1, ['flag'=>0], 1); //所扫的件已是分拨中心的件了
                        }else if($piece->state_in==3 && (!in_array($piece->worker_id , static::$centerPoint)
                                || (in_array($piece->worker_id , static::$centerPoint) && ($worker->id != $piece->worker_id)) )) {
                            $this->writeAesJson(1, ['flag'=>1], 1); //所扫的件不是分拨中心的件了
                        }else if($piece->state_in>3) {
                            $this->writeAesJson(0, '已运出过站点' , 1); //所扫的件不是分拨中心的件了
                        }
                    }else
                        $this->writeAesJson(0, '查无此件', 1);
                }else
                    $this->writeAesJson(0, '件码传输格式有误', 1);
            }else
                $this->writeAesJson(0, '件码不能为空', 1);
        }
    }


}